<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="deviceNo">
        <el-input v-model="queryParams.deviceNo" placeholder="请输入设备编号" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd" v-hasPermi="['iot:broadcast:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:broadcast:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:broadcast:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button id="openbtn" type="success" :plain="selectedRows.length === 0" size="mini" :disabled="selectedRows.length === 0" @click="handleTurnOn">
          <i class="el-icon-video-play" style="font-size: 1.3em; margin-right: 6px;"/>播放广播</el-button>
<el-button id="closebtn" type="danger" :plain="selectedRows.length === 0" size="mini" :disabled="selectedRows.length === 0" @click="handleTurnOff(selectedRows)">
          <i class="el-icon-video-pause" style="font-size: 1.3em; margin-right: 6px;"/>关闭广播</el-button>
      </el-col>
<!--      <el-col :span="2.1" style="margin-left:5px;display:flex;align-items:center;">
          <span style="font-size:12px;margin-right:5px;">调音量</span>
            <el-select v-model="sldVolumeLvl" :disabled="selectedRows.length===0" size="mini" style="width:100px;" @change="updtVolume">
              <el-option v-for="item in volumeOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
      </el-col>
    <el-col :span="1.5">
    <el-button type="primary" plain icon="el-icon-time" size="small" @click="openDialog" v-hasPermi="['iot:broadcast:dotime']"
      :disabled="selectedRows.length===0" :class="{'plain-button':selectedRows.length===0}">定时</el-button></el-col>
    <el-col :span="1.5">
    <el-button type="warning" plain icon="el-icon-upload" size="small" @click="sendDialog" v-hasPermi="['iot:broadcast:doxxx']"
      :disabled="selectedRows.length===0" :class="{'plain-button':selectedRows.length===0}">节目发送</el-button></el-col> -->
    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar></el-row>
    <el-table v-loading="loading" :data="broadcastList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="false"/>
      <el-table-column label="客户" align="center" prop="nickName" width="155" show-overflow-tooltip/>
      <el-table-column label="项目" align="center" prop="projectname" width="155" show-overflow-tooltip/>
      <el-table-column label="设备编号" align="center" prop="deviceNo" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="灯杆序号" align="center" prop="boxNo" />
      <el-table-column label="在线状态" align="center" width="86">
        <template slot-scope="scope">
          <div class="status-container"><img :src="getStateImags(scope.row.state)" alt="在线状态" style="width:22px;height:22px;"/></div>
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center">
        <template slot-scope="scope">
          <div class="status-container"><img :src="getStatusImage(scope.row.dcStatus)" alt="工作状态" style="width:40px;height:40px;"/></div>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" prop="deviceType" align="center" width="80">
        <template slot-scope="scope"><dict-tag :options="dict.type.bc_type" :value="scope.row.deviceType"/></template>
      </el-table-column>
      <el-table-column label="音量" prop="dcVolumeLevel" align="center" width="80">
        <template slot-scope="scope"><dict-tag :options="dict.type.iot_ds_volume" :value="scope.row.dcVolumeLevel"/></template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="156">
        <template slot-scope="scope">{{scope.row.createTime}}</template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="156">
        <template slot-scope="scope">{{scope.row.updateTime||'未更新'}}</template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:hgdisplay:edit']">修改</el-button>
  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:hgdisplay:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes" @pagination="getList"/>
<bdcast-uusser ref="bdcast"/>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户名称" filterable style="width:100%" @change="handleNicknameChange">
            <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目名称" filterable style="width:100%" @change="handleProjectnameChange">
            <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" filterable style="width:100%">
            <el-option v-for="dict in dict.type.bc_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input v-model="form.deviceNo" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="灯杆序号" prop="boxNo">
          <el-input v-model="form.boxNo" placeholder="请输入灯杆序号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'
import { listBroadcast, getBroadcast, delBroadcast, addBroadcast, updateBroadcast } from "@/api/iot/broadcast";
import request from '@/utils/request'
import bdcastUusser from "./bdcastItem"
export default {
  dicts:['bc_type'],
  name: "Broadcast",
  components:{bdcastUusser},
  data() {
    return {
      pageSizes: [10,20,30,50],
      pollInterval: null, // 轮询定时器
      options: [],
      projectnameOptions: [],
      selectedRows: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      broadcastList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        customerId: null,
        projectId: null,
        deviceType: null,
        deviceNo: null,
        deviceName: null,
        dcStatus: null,
        dcVolumeLevel: null,
        boxNo: null,
        state: null,
      },
      form: {},
      rules: {
        customerId: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        projectId: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        deviceType: [{ required: true, message: "设备类型不能为空", trigger: "change" }],
        deviceNo: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
        deviceName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
    this.startPolling(); // 开始轮询
  },
  beforeDestroy() {
    clearInterval(this.pollInterval);
  },
  methods: {
    handleTurnOn() {
      this.reset();
      this.$refs.bdcast.show(this.selectedRows);
    },
    startPolling() {// 每10分钟秒轮询一次数据
      this.pollInterval = setInterval(this.getList, 600000);},
    getStatusImage(status) {
      return status==='1'?require('@/assets/bigScreen/img/yxon.png'):require('@/assets/bigScreen/img/yxoff.png');
    },
    getStateImags(status) {
      return status==='1'?require('@/assets/bigScreen/img/wifion.png'):require('@/assets/bigScreen/img/wifi.png');
    },
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        console.log(`Selected ID: ${selectedId}, nickName: ${selectedOption.nickName}`);
        this.form.customerId = selectedOption.userId;
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        console.log('Selected Project ID:', selectedOption.id);
        console.log('Selected Project Name:', selectedOption.projectname);
        this.form.projectId = selectedOption.id;
      } else {console.error('No matching data found for value:', value);}
    },
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList=response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
          console.log("获取用户列表数据", this.options);
        }
      } catch (error) {console.error('获取用户列表失败', error);}
    },
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList=response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
          console.log("获取项目名称", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    getList() {
      this.loading = true;
      listBroadcast(this.queryParams).then(response => {
        this.broadcastList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        adminId: null,
        customerId: null,
        projectId: null,
        deviceType: null,
        deviceNo: null,
        deviceName: null,
        dcStatus: "0",
        dcVolumeLevel: null,
        boxNo: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selectedRows = selection;
      this.broadcastList.forEach(row => {
        row.checked = selection.some(item => item.id === row.id);
      });
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBroadcast(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBroadcast(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess("修改成功");
              }
              this.open = false;
              this.getList();
            });
          } else {
            addBroadcast(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess("新增成功");
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除慧光智慧广播编号为"' + ids + '"的数据项？').then(function() {
        return delBroadcast(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('iot/broadcast/export', {
        ...this.queryParams
      }, `broadcast_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
